//
//  UserSignController.m
//  HarmonizePub
//
//  Created by rzhy on 16/9/2.
//  Copyright © 2016年 Zy. All rights reserved.
//

#import "UserSignController.h"
#import "Config.h"
#import <JKCountDownButton.h>
#import "SVProgressHUD.h"
#import "Utils.h"

@interface UserSignController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *phoneNumField;
@property (weak, nonatomic) IBOutlet UITextField *passWordField;
@property (weak, nonatomic) IBOutlet UITextField *verificationCodeField;
@property (weak, nonatomic) IBOutlet JKCountDownButton *getCodeButton;
@property (weak, nonatomic) IBOutlet UIButton *signButton;

@end

@implementation UserSignController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"用户注册";
    self.getCodeButton.layer.cornerRadius  = 5.0f;
    self.getCodeButton.layer.masksToBounds = NO;
    self.signButton.layer.cornerRadius  = 5.0f;
    self.signButton.layer.masksToBounds = NO;
    [self.phoneNumField becomeFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 注册
- (IBAction)signEvent:(UIButton *)sender {
    NSString *phoneString    = [_phoneNumField.text stringRemoveSpecialSymbol:@" "];
    NSString *passwordString = [_passWordField.text stringRemoveSpecialSymbol:@" "];
    NSString *codeString     = [_verificationCodeField.text stringRemoveSpecialSymbol:@" "];
    if (!phoneString || [phoneString isEqualToString:@""])
         [self setAlertViewWithMessage:@"请输入手机号码!"];
     else if (![Utils matchingTelNumber:phoneString])
         [self setAlertViewWithMessage:@"请输入正确的手机号码!"];
     else if (!passwordString || [passwordString isEqualToString:@""])
        [self setAlertViewWithMessage:@"请输入密码!"];
    else if (passwordString.length <= 0 || passwordString.length > 16)
        [self setAlertViewWithMessage:@"请输入正确的密码!\n密码由1-16位数字和字母组成!"];
     else if (!codeString || [codeString isEqualToString:@""])
        [self setAlertViewWithMessage:@"请输入验证码!"];
     else {
         NSDictionary *param = @{@"phone" : phoneString, @"password" : passwordString, @"deviceType" : @"1", @"code" : codeString};
         __weak typeof(self) weakSelf = self;
         [HTTPSTool GETRequestWithPath:XHUserSignPath params:param success:^(NSDictionary * _Nonnull JSON) {
             [_getCodeButton stopCountDown];
             if ([_delegate respondsToSelector:@selector(signSuccessWithUserName:passWord:)])
                 [_delegate signSuccessWithUserName:phoneString passWord:passwordString];
             [weakSelf dismissViewControllerAnimated:YES completion:nil];
         }];
    }
}

#pragma mark - 获取验证码
- (IBAction)getCodeButtonEvent:(JKCountDownButton *)sender {
    NSString *phoneNum = [_phoneNumField.text stringRemoveSpecialSymbol:@" "];
    if (!phoneNum || [phoneNum isEqualToString:@""])
        [self setAlertViewWithMessage:@"请输入手机号码!"];
    else if (![Utils matchingTelNumber:phoneNum])
        [self setAlertViewWithMessage:@"请输入正确的手机号码!"];
    else {
        [self.view endEditing:NO];
        sender.enabled = NO;
        [sender startCountDownWithSecond:60];
        [sender countDownChanging:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
            countDownButton.backgroundColor = [UIColor lightGrayColor];
            return [NSString stringWithFormat:@"剩余%lu秒", (unsigned long)second];
        }];
        [sender countDownFinished:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
            countDownButton.enabled = YES;
            countDownButton.backgroundColor = RGBColor(125, 26, 31);
            return @"重新获取";
        }];
        [SVProgressHUD show];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
        NSDictionary *param = @{@"phone" : phoneNum, @"type" : XHType};
        [HTTPSTool POST:XHCodePath params:param cookie:nil success:^(NSDictionary * _Nonnull JSON) {
//            XHLog(@"获取验证码 -> JSON: %@", JSON)
            [SVProgressHUD dismiss];
            NSInteger result = [JSON[@"ret"] integerValue];
            if (result > 1) {
                [self setAlertViewWithMessage:JSON[@"msg"]];
                [sender stopCountDown];
            } else if (result == 1) {
                [ZYToast showBottomText:@"验证码发送成功!"];
                _signButton.enabled = YES;
                _signButton.backgroundColor = RGBAColor(125, 26, 31, 0.7);
            } else {
                [sender stopCountDown];
            }
        } failure:^(NSError * _Nonnull error) {
            [SVProgressHUD dismiss];
            [sender stopCountDown];
        }];
    }
}

#pragma mark - 显示/隐藏密码
- (IBAction)switchShowAndHidenPassWordEvent:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.passWordField.secureTextEntry = !sender.selected;
}

#pragma mark - 返回
- (IBAction)back:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)setAlertViewWithMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:NO];
}

@end
